from rest_framework import generics, status, permissions
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework_simplejwt.exceptions import AuthenticationFailed
from rest_framework_simplejwt.tokens import RefreshToken
from django.utils.translation import gettext as _   
from .models import CustomUser
from .serializers import RegisterSerializer, UserProfileSerializer
from rest_framework.pagination import PageNumberPagination
from rest_framework_simplejwt.views import TokenObtainPairView
from .serializers import CustomTokenObtainPairSerializer

# 定义分页类
class CustomUserPagination(PageNumberPagination):
    page_size = 10  # 每页显示的用户数量
    page_size_query_param = 'page_size'
    max_page_size = 100  # 最大分页数


# 自定义登录视图
class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer

    def post(self, request, *args, **kwargs):
        try:
            return super().post(request, *args, **kwargs)
        except AuthenticationFailed as e:
            # 捕获认证错误并返回自定义格式的 200 响应
            error_data = e.detail if isinstance(e.detail, dict) else {
                'status': 'error',
                'code': 'authentication_error',
                'message': str(e.detail)
            }
            return Response(error_data, status=status.HTTP_200_OK)
        except Exception as e:
            # 处理其他意外错误
            return Response({
                'status': 'error',
                'code': 'server_error',
                'message': '服务器发生意外错误'
            }, status=status.HTTP_200_OK)

# 用户注册视图
class RegisterView(generics.CreateAPIView):
    serializer_class = RegisterSerializer
    permission_classes = [AllowAny]  # 允许任何人注册

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 处理重复用户名或邮箱
        if CustomUser.objects.filter(username=serializer.validated_data['username']).exists():
            return Response({'error': _('Username already exists.')}, status=status.HTTP_400_BAD_REQUEST)

        user = serializer.save()
        refresh = RefreshToken.for_user(user)

        return Response({
            'refresh': str(refresh),
            'access': str(refresh.access_token),
            'user_id': user.id,
            'username': user.username,  # 返回用户名
        }, status=status.HTTP_201_CREATED)

# 用户资料查看和更新视图
class UserProfileView(generics.RetrieveUpdateAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = UserProfileSerializer
    permission_classes = [permissions.IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]  # 添加解析器以处理文件上传

    def get_object(self):
        return self.request.user  # 获取当前登录用户

    def post(self, request, *args, **kwargs):
        user = self.get_object()  # 获取当前登录用户
        serializer = UserProfileSerializer(user, data=request.data, partial=True)  # 使用 partial 允许部分更新
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get_serializer_context(self):
        # 将 request 对象传入上下文
        return {'request': self.request}

# 自定义权限类，检查是否是管理员
class IsAdminUser(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_staff

# 管理员查看用户列表的视图，带分页功能
class AdminUserListView(generics.ListAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = UserProfileSerializer
    permission_classes = [IsAdminUser]
    pagination_class = CustomUserPagination

# 管理员删除用户的视图
class AdminUserDeleteView(generics.DestroyAPIView):
    queryset = CustomUser.objects.all()
    permission_classes = [IsAdminUser]
